<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:moldInventory:add']"
        >
          新增模具盘点
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-s-order"
          size="mini"
          @click="open = true"
          v-hasPermi="['project:moldInventory:real']"
        >
          实盘
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-success"
          size="mini"
          @click="handleClose"
          v-hasPermi="['project:moldInventory:finish']"
        >
          盘点完成
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:moldInventory:export']"
        >
          导出
        </el-button>
      </el-col>
      <!-- 分页效果 -->
      <el-col :span="2.2" style="position: absolute; right: 0px; top: 0">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 查询对话框   -->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="400px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="24">
          <el-form-item label="开单日期">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 280px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>

    <!-- 上表 -->
    <el-table
      highlight-current-row
      border
      stripe
      v-loading="loading"
      height="calc(50% - 80px)"
      :data="moldInventoryList"
      @row-click="clickAddButton"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column
        label="#"
        type="index"
        fixed="left"
        width="40"
        align="center"
      />
      <el-table-column
        label="模具盘点开始时间"
        :show-overflow-tooltip="true"
        align="center"
        prop="createTime"
      />
      <el-table-column
        label="模具盘点结束时间"
        :show-overflow-tooltip="true"
        align="center"
        prop="updateTime"
      />
      <el-table-column
        label="模具盘点开始人员"
        :show-overflow-tooltip="true"
        align="center"
        prop="createBy"
      />
      <el-table-column
        label="模具盘点结束人员"
        :show-overflow-tooltip="true"
        align="center"
        prop="updateBy"
      />
      <el-table-column
        label="模具盘点状态"
        :show-overflow-tooltip="true"
        align="center"
        prop="state"
      />
    </el-table>

    <!-- 下表 -->
    <el-table
      highlight-current-row
      border
      stripe
      height="calc(50% + 20px)"
      @scrollBottom="load"
      :loading="loadingChild"
      :data="moldChildList"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="#" type="index" width="40" align="center" />
      <el-table-column label="台账">
        <el-table-column
          label="客户名称"
          :show-overflow-tooltip="true"
          width="120"
          align="center"
          prop="cusName"
        />
        <el-table-column
          label="模具编号"
          :show-overflow-tooltip="true"
          align="center"
          prop="mjmMjbh"
        />
        <el-table-column
          label="模具名称"
          :show-overflow-tooltip="true"
          align="center"
          prop="mjmMjmc"
        />
        <el-table-column
          label="状态"
          :show-overflow-tooltip="true"
          width="80"
          align="center"
          prop="mjmMjzt"
        >
          <template #default="scope">
            <dict-tag :options="moldStateOptions" :value="scope.row.mjmMjzt" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="实盘">
        <el-table-column
          label="模具编号"
          :show-overflow-tooltip="true"
          align="center"
          prop="moldCode"
        />
        <el-table-column
          label="存放位置"
          :show-overflow-tooltip="true"
          align="center"
          prop="moldLocation"
        />
        <el-table-column
          label="盘点人"
          :show-overflow-tooltip="true"
          align="center"
          prop="createBy"
        />
      </el-table-column>
      <el-table-column
        label="盘点盈亏"
        :show-overflow-tooltip="true"
        width="80"
        align="center"
        prop="inventoryState"
      />
    </el-table>

    <el-dialog
      title="实盘"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模具编号" prop="moldCode">
          <el-autocomplete
            class="input"
            v-model="form.moldCode"
            :fetch-suggestions="querySearch"
            placeholder="请输入模具编号"
            clearable
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="地点" prop="moldLocation">
          <el-input
            type="textarea"
            v-model="form.moldLocation"
            placeholder="请输入地点"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="handleOpen">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  beginMoldInventory,
  endMoldInventory,
  exportMoldInventory,
  listMoldInventory,
  listMoldInventoryChild,
  realTransaction,
} from "@/api/project/moldInventory";
import { getMjmByBhOrMc } from "@/api/project/mjmMstr";

export default {
  name: "MoldInventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingChild: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      openSearch: false,
      // 总条数
      total: 0,
      totalChild: 0,
      moldInventoryList: [],
      moldChildList: [],
      // 开单日期时间范围
      dateRange: [
        this.$moment().add(-1, "month").startOf("month").toDate(),
        this.$moment().endOf("month").toDate(),
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParamsChild: {
        pageNum: 1,
        pageSize: 50,
        parentId: null,
      },
      // 模具单状态
      moldStateOptions: [],
      // 模具列表
      modelList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        moldCode: [
          { required: true, message: "模具编号不能为空", trigger: "blur" },
        ],
        moldLocation: [
          { required: true, message: "地点不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getAllDicts("mould_status").then((response) => {
      this.moldStateOptions = response.data;
    });
    getMjmByBhOrMc().then((res) => {
      res.rows.forEach((r) => {
        r.value = r.mjmMjbh;
      });
      this.modelList = res.rows;
    });
    this.getList();
  },
  methods: {
    /** 查询模具盘点列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.dateRange && "" != this.dateRange) {
        this.queryParams.params["beginDate"] = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParams.params["endDate"] = this.moment(
          this.dateRange[1]
        ).format("YYYY-MM-DD HH:mm:ss");
      }
      this.moldInventoryList = [];
      this.queryParams.pageNum = 1;
      listMoldInventory(this.queryParams).then((response) => {
        this.moldInventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
        if (
          this.moldInventoryList != null &&
          this.moldInventoryList.length > 0
        ) {
          this.queryParamsChild.parentId = this.moldInventoryList[0].id;
          this.getListChild();
        } else {
          this.moldInventoryList = [];
          this.moldChildList = [];
        }
      });
    },
    getListChild() {
      this.loadingChild = true;
      this.moldChildList = [];
      this.queryParamsChild.pageNum = 1;
      listMoldInventoryChild(this.queryParamsChild).then((response) => {
        this.moldChildList = response.rows;
        this.totalChild = response.total;
        this.loadingChild = false;
      });
    },
    load() {
      if (
        this.queryParamsChild.pageNum <
        Math.ceil(this.totalChild / this.queryParamsChild.pageSize)
      ) {
        this.queryParamsChild.pageNum++;
        listMoldInventoryChild(this.queryParamsChild).then((response) => {
          this.moldChildList = this.moldChildList.concat(response.rows);
          this.totalChild = response.total;
        });
      }
      return 0;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        moldCode: null,
        moldLocation: null,
      };
      this.resetForm("form");
    },
    querySearch(queryString, cb) {
      let restaurants = this.modelList;
      let results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    /** 表格点击事件 */
    clickAddButton(row) {
      this.queryParamsChild.parentId = row.id;
      this.getListChild();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.moldChildList = [];
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSearch() {
      this.reset();
      this.title = "查询模具盘点单";
      this.openSearch = true;
    },
    handleAdd() {
      this.$confirm("是否新增模具盘点单？", "确认", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          beginMoldInventory().then((res) => {
            this.getList();
            this.msgSuccess(res.msg);
          });
        })
        .catch(() => {});
    },
    handleOpen() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          realTransaction(this.form).then((res) => {
            this.msgSuccess(res.msg);
            this.open = false;
            this.reset();
            this.getListChild();
          });
        }
      });
    },
    handleClose() {
      this.$confirm("是否确认模具盘点完成？", "警告", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          endMoldInventory().then((res) => {
            this.getList();
            this.msgSuccess(res.msg);
          });
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParamsChild;
      this.$confirm("是否导出所有模具盘点数据项?", "确认", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportMoldInventory(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped></style>
